package studentManage.model;

import java.io.Serializable;
import java.util.UUID;

import studentManage.util.MajorUtil;
import studentManage.util.StudentUtil;

public class StudentModel implements Serializable{

	/**
	 * 序列化
	 */
	private static final long serialVersionUID = 1L;
	
	// id和用户名不可重复
	private Integer id;// 学生编号-->可不用，数据库自增
	private String user;// 用户名
	private String pass;// 密码
	private String name;// 姓名
	private int sex;// 性别 -- 1-男 2-女
	private String majCode;// 专业id

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {// id不可重复
		if (seach(id)) {// false重复
			this.id = id;
			return;
		}
		System.out.println("id重复，已为您自动生成一个id！");
		this.id = (int) (Math.random() * 2000000000 + 0);
		System.out.println("id："+this.id);
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		if (seach(user)) {
			this.user = user;
			return;
		}
		System.out.println("用户名重复，已为您自动生成一个用户名！");
		this.user = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10);
		System.out.println("用户名："+this.user);
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		if (sex == 1) {
			return "男";
		} else if (sex == 2) {
			return "女";
		}
		return "未指定";
	}

	public void setSex(String sex) {
		if (sex.equals("男")) {// 男生
			this.sex = 1;
			return;
		} else if (sex.equals("女")) {// 女生
			this.sex = 2;
			return;
		}
		this.sex = 0;
	}

	public String getMajCode() {
		MajorUtil maj = new MajorUtil();
		String majName = maj.select(this.majCode).getName();
		return majName;
	}

	public void setMajCode(String majCode) {
		this.majCode = majCode;
	}

	/**
	 * 查询集合中是否已经存在相同id或者用户名
	 * 
	 * 方法只能在本类中使用
	 * 
	 * @param id
	 * @param user
	 * @return
	 */
	private boolean seach(Integer id, String user) {
		if (id != null) {
			for (StudentModel stu : StudentUtil.students) {
				if (stu.getId() == id)
					return false;
			}
		}
		if (user != null) {
			for (StudentModel stu : StudentUtil.students) {
				if (stu.getUser().equals(user)) {
					return false;
				}
			}
		}
		return true;
	}

	private boolean seach(Integer id) {
		return seach(id, null);
	}

	private boolean seach(String user) {
		return seach(null, user);
	}

	@Override
	public String toString() {
		return "StudentModel [id=" + id + ", user=" + user + ", pass=" + pass + ", name=" + name + ", sex=" + sex
				+ ", majCode=" + majCode + "]";
	}
	
}
